import React, { FC } from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth } from '../components/AuthContext';
import Error_403 from '/@/views/NotFound/Error_403';
interface RouterAuthProps {
  component: React.ComponentType;
  requiredRoles: string[];
  isAuthMenu: boolean;
  redirectTo?: string;
}

const RouterAuth: FC<RouterAuthProps> = ({
  component: Component,
  requiredRoles,
  isAuthMenu,
  redirectTo = '/login',
}): any => {
  const { auth } = useAuth();
  // 未登录，跳转到登录界面
  if (!auth) return <Navigate to={redirectTo} replace />;

  // 权限不足，渲染不匹配组件或跳转到404页面
  const hasAuth = requiredRoles.some((r) => r === auth);
  if (!hasAuth) {
    return isAuthMenu ? <Error_403 /> : <Navigate to='/404' replace />;
  }

  return Component;
};

export default RouterAuth;
